/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mp3organizer;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;

/**
 *
 * @author Aderthad
 */
public class Organize implements Actionable {

    @Override
    public void work(List<Mp3Orginizer.Album> albums) {
        File outputFolder = new File(Mp3Orginizer.getFolder().getAbsolutePath() + File.separator + "_NEW");

        outputFolder.mkdir();

        for (Mp3Orginizer.Album al : albums) {

            System.out.println("Album " + al.getName() + " Songs " + al.getSongs().size());

            File albumFolder = new File(outputFolder.getAbsolutePath() + File.separator + al.getName());

            if (!albumFolder.mkdir() && !albumFolder.exists()) {
                System.out.println("ERROR: Couldn't create folder " + albumFolder.getAbsolutePath());
                return;
            }

            for (Mp3Orginizer.Song s : al.getSongs()) {
                try {
                    String songName = "_UNSORTED".equals(al.getName()) ? s.getName() : String.format("%02d", Integer.parseInt(s.getTrackNum())) + ". " + s.getName() + ".mp3";
                    songName += ".mp3";
                    Files.copy(s.getPath(), new File(albumFolder.toPath() + File.separator + songName).toPath(), StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException ex) {
                    System.out.println(ex.getMessage());
                }
            }
        }
    }

}
